package edu.hunau.cxb19.oop.class32.tcp.v6;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

/**
 * 客户端可以持续的向服务器发送消息
 * 
 * @author hb
 *
 *         2020-04-21 16:29:12
 */
public class ClientTcp {
	private Socket socket;
	private String name;

	public ClientTcp(String name) {
		try {
			this.name = name;
			socket = new Socket("localhost", 8088);
		} catch (Exception e) {
			// Todo Auto-generated catch block
			e.printStackTrace();
		}
	}

	public void start() {
		try {
			// 启动接收消息的线程
			Thread readMessageThread = new Thread(new ServerHandler());
			readMessageThread.setDaemon(true);
			readMessageThread.start();

			// 向服务器发送消息,获得输出流 (通过main线程发消息)
			OutputStream os = socket.getOutputStream();
			// 写出数据
			PrintWriter pw = new PrintWriter(os, true);

			Scanner sc = new Scanner(System.in);
			while (true) {
				String data = sc.nextLine();
				pw.println(name + ":" + data);
				if ("exit".equals(data)) {
					break;
				}
			}

		} catch (Exception e) {
			// TODO: handle exception
		} finally {
			if (socket != null) {
				try {
					socket.close();
				} catch (IOException e) {
					throw new RuntimeException(e);
				}
			}
		}

	}

	/**
	 * 提供读取消息的线程
	 */
	private class ServerHandler implements Runnable {
		@Override
		public void run() {
			try {
				// 读取客户端的消息
				InputStream is = socket.getInputStream();
				InputStreamReader isr = new InputStreamReader(is, "utf-8");
				BufferedReader br = new BufferedReader(isr);
				while (true) {
					System.out.println(br.readLine());
				}
			} catch (Exception e) {
				// TODO: handle exception
			}
		}

	}

	public static void main(String[] args) {
		String name="王五";
		System.out.println(name+"的客户端");
		new ClientTcp(name).start();
	}
}
